package com.suixuan.spring.web.controller.security;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/dwz")
public class DwzController {
    @RequestMapping(value = "/loginDialog", method = { RequestMethod.GET })
    public String loginDialog() {

        return "dwz/loginDialog";
    }

    private static List<Map<String, String>> tableValue = new ArrayList<Map<String, String>>();

    @RequestMapping(value = "/table")
    public String table(HttpServletRequest request) {
        if (CollectionUtils.isEmpty(tableValue)) {
            for (int i = 0; i < 20; i++) {
                Map<String, String> value = new HashMap<String, String>();
                value.put("cid", "cid_" + i);
                value.put("cname", "cname_" + i);
                value.put("ctype", "ctype_" + i);
                tableValue.add(value);
            }
        }

        request.setAttribute("tableValue", tableValue);
        return "dwz/table";
    }

    @RequestMapping(value = "/addTable")
    public String addTable() {
        return "dwz/addTable";
    }

    @RequestMapping(value = "/saveTable")
    public void saveTable(HttpServletResponse response) throws IOException {
        int i = tableValue.size();
        Map<String, String> value = new HashMap<String, String>();
        value.put("cid", "cid_" + i);
        value.put("cname", "cname_" + i);
        value.put("ctype", "ctype_" + i);
        tableValue.add(value);

        JsonResult jr = new JsonResult("200", "", "", "", "closeCurrent", "");
        JSONObject jo = JSONObject.fromObject(jr);

        response.getWriter().print(jo.toString());

    }

    @RequestMapping(value = "/delTable")
    public void delTable(HttpServletRequest request, HttpServletResponse response) throws IOException {

        tableValue.remove(Integer.parseInt(request.getParameter("index")));

        JsonResult jr = new JsonResult("200", "", "", "", "", "");
        JSONObject jo = JSONObject.fromObject(jr);

        response.getWriter().print(jo.toString());

    }
}
